package com.levi.test.util;

import io.netty.handler.codec.http.HttpMethod;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import static com.levi.test.constant.ExecuteCommonData.CHARSET;
import static com.levi.test.constant.ExecuteCommonData.TIMEOUTL;
import static com.levi.test.constant.ExecuteCommonData.rpcPath;
import static com.levi.test.constant.ExecuteCommonData.rpcPort;
import static com.levi.test.constant.ExecuteCommonData.LOCAL;

public class ExecuteHttpUtil {

    public static String http(String data) {
        try {
            System.out.println("=============================================");
            System.out.println("请求：" + data);
            System.out.println("=============================================");
            data = SecretUtil.secret(data, true);
            URL uu = new URL(LOCAL + rpcPort + rpcPath);
            HttpURLConnection con = (HttpURLConnection) uu.openConnection();
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setUseCaches(false);
            con.setConnectTimeout(TIMEOUTL);
            con.setReadTimeout(TIMEOUTL);
            con.setRequestProperty("Connection", "Keep-Alive");
            con.setRequestMethod(HttpMethod.POST.name());
            OutputStream os = con.getOutputStream();
            os.write(data.getBytes(CHARSET));
            //con.connect();
            InputStream inputStream = con.getInputStream();
            String resp = stream2String(inputStream);
            System.out.println("响应：" + resp);
            System.out.println("=============================================");
            con.disconnect();
            return resp;
        } catch (Exception e) {
            System.err.println(e.getMessage());
            return null;
        }
    }

    private static String stream2String(InputStream is) throws IOException {
        StringBuilder str = new StringBuilder();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        String line = null;
        while ((line = reader.readLine()) != null) {
            str.append(line);
        }
        return str.toString();
    }
}
